package com.xz.util;

import com.alibaba.fastjson.JSONObject;
import nuonuo.open.sdk.NNOpenSDK;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class RealUtil {

    /**
     * 发起POST请求
     *
     * @param url       url
     * @param paramJson 参数的json格式
     */
    public static String sendPost(String url, String paramJson) {
        // 创建httpClient实例对象
        HttpClient httpClient = new HttpClient();
        // 设置httpClient连接主机服务器超时时间：15000毫秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
        // 创建post请求方法实例对象
        PostMethod postMethod = new PostMethod(url);
        // 设置post请求超时时间
        postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        postMethod.addRequestHeader("Content-Type", "application/json");
        postMethod.addRequestHeader("appKey", "32033532");
        postMethod.addRequestHeader("accessToken", "370743d065d1e97e3c12430ksyt5djks");
        try {
            //json格式的参数解析
            StringRequestEntity entity = new StringRequestEntity(paramJson, "application/json", "UTF-8");
            postMethod.setRequestEntity(entity);
            httpClient.executeMethod(postMethod);
            String result = postMethod.getResponseBodyAsString();
            postMethod.releaseConnection();
            return result;
        } catch (IOException e) {
        }
        return null;
    }
    public static String httpPost(String urlStr,Map<String,Object> params){
        URL connect;
        StringBuffer data = new StringBuffer();
        try {
            connect = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection)connect.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);//post不能使用缓存
            connection.setInstanceFollowRedirects(true);
//            connection.setRequestProperty("accept", "*/*");
//            connection.setRequestProperty("connection", "Keep-Alive");
//            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Content-Type", "application/json");
//            connection.setRequestProperty("appKey","32033532");
            connection.setRequestProperty("accessToken","370743d065d1e97e3c12430lap6zshns");
            connection.setRequestProperty("method","nuonuo.billRecognition.queryBillOpenByTaskId");
            connection.setRequestProperty("X-Nuonuo-Sign","9FC8809607AC483B");
            connection.setRequestProperty("userTax","555555");
            OutputStreamWriter paramout = new OutputStreamWriter(
                    connection.getOutputStream(),"UTF-8");
            String paramsStr = "";   //拼接Post 请求的参数
            for(String param : params.keySet()){
                paramsStr += "&" + param + "=" + params.get(param);
            }
            if(!paramsStr.isEmpty()){
                paramsStr = paramsStr.substring(1);
            }
            paramout.write(paramsStr);
            paramout.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                data.append(line);
            }

            paramout.close();
            reader.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return data.toString();
    }


    public static void main(String[] args) {
//        JSONObject json1=new JSONObject();
//        json1.put("senid",'0');
//        json1.put("nonce", "jsddkj");
//        json1.put("timestamp","FacilityServer.getFacilityList");
//        json1.put("appkey","FacilityServer.getFacilityList");
//        json1.put("taskId","FacilityServer.getFacilityList");
//        Map<String, Object> map=new HashMap<>();
//        map.put("DATA", json1.toString());
//        String url="https://sdk.nuonuo.com/open/v1/services";
//        System.out.println(httpPost(url,map));

        NNOpenSDK sdk = NNOpenSDK.getIntance();
        String taxnum = "2354545789"; // 授权企业税号String appKey = "Hn***XL";
        String appSecret = "9FC8809607AC483B";
//        String method = "nuonuo.billRecognition.recognizeBillOpenSingle"; // API方法名 单
        String method = "nuonuo.billRecognition.queryBillOpenByTaskId";
        String token = "370743d065d1e97e3c12430ksyt5djks"; // 访问令牌
         String content = "{\"taskId\": \"16039558021665307195TNBDM\"}";
//        String content =  "{" + "\"callBackUrl\":\"http://xxxx/testCallBackSuccess.do\"," + "\"source\":\"0\"," + "\"fileId\":\"e4369f7dcb774637aede8a052c061403\"" + "}";
        String url = "https://sdk.nuonuo.com/open/v1/services"; // SDK请求地址
        String senid = UUIDGenerator.generate().replace("-", ""); // 唯一标识，由企业自己生成32位随机码
        String result = sdk.sendPostSyncRequest(url, senid, "32033532", appSecret, token, taxnum, method, content);
        System.out.println(result);
    }
}
